# -*- encoding:utf-8 -*-
"""
-文件：wallet.py
-说明：钱包类
-作者：tlj
一个合法的比特币地址背后必定隐藏着一对合法的验证密钥及签名密钥，
定义了一个 Wallet 类即钱包类，来管理这对密钥
"""

import ecdsa
import pickle
from .address import Address



class Wallet:
    def __init__(self, comments=''):
        self.comments = comments
        self.sign_key = ecdsa.SigningKey.generate(curve=ecdsa.SECP256k1)
        self.verify_key = self.sign_key.get_verifying_key()
        self.address = Address(self.verify_key)

    def __repr__(self):
        return "Wallet(address={}, comments={})".format(self.address, self.comments)


class Wallets:
    """
    钱包管理类
    """
    WALLETS_FILE = 'data/wallets{}.db'

    def __init__(self, node_id):
        self.db_file = Wallets.WALLETS_FILE.format(node_id)
        # print(self.db_file)
        try:
            with open(self.db_file, 'rb') as f:
                self._wallets = pickle.load(f)
        except FileNotFoundError:
            print('新建钱包', self.db_file)
            self._wallets = {}

    def save_to_file(self):
        print("保存钱包", self.db_file)
        with open(self.db_file, 'wb') as f:
            pickle.dump(self._wallets, f)

    def get_wallet(self, add_str):
        return self._wallets[add_str]

    def create_wallet(self, comments=''):
        w = Wallet(comments)
        add_str = w.address.get_address_str()
        self._wallets[add_str] = w
        return w

    def get_addresses(self):
        return [addr for addr in self._wallets.keys()]
